package com.wad.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.wad.manager.service.ValidateCodeService;
import com.wad.vo.system.ValidateCodeVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wad
 * @date 2023/11/29 16:30
 * @project e-commerce
 **/
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {


    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //生成图片验证码
    @Override
    public ValidateCodeVo generateValidateCode() {

        //通过工具生成图片的验证码 hutool
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String code = circleCaptcha.getCode(); //生成四位验证码的值
        String imageBase64 = circleCaptcha.getImageBase64(); //返回图片验证码用base64进行编码
        //把验证码存储到redis里面，设置redis的key：uuid redis的value：验证码的值 设置过期时间
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:validate"+key,code,5, TimeUnit.MINUTES);
        //返回ValidateCodeVo对象
        ValidateCodeVo validateCodeVo=new ValidateCodeVo();
        validateCodeVo.setCodeKey(key); //redis存储的key
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        return validateCodeVo;
    }
}
